<?php
namespace Application\Model\Dao;
use Zend\Config\Reader\Xml;
use Zend\Db\Adapter\Driver\ResultInterface;
use Zend\Db\ResultSet\ResultSet;
use Application\Service\XmlService;
use Zend\Db\Adapter\Driver\Mysqli\Statement;
use Zend\Form\Annotation\Object;

class UserDao extends BaseDao
{


	/**
	 * Select query
	 * @var unknown
	 */
	public static $SELECT_BY_ID = "select * from user where id = ? ";

	public static $SELECT_BY_EMAIL = "select * from user where email = ? limit 1";

	public static $SELECT_BY_EMAIL_PASSWORD = "select *  from user where email = ? and password = ?";

	public static $SELECT_BY_EMAIL_SECRET = "select *  from user where email = ? and secret = ?";

	public static $RECENT_USERS =  "select user.id as id,name,password,flatNumber,profession,email,phone, user.photoset as photoset,attributeRow,similar,
          user_group.photoset as gphotoset, title, description, type, group_id
            from user left join group_user on user.id = group_user.user_id  left join
            user_group on group_user.group_id=user_group.id limit 100";


    public static $SELECT_USER_FIELDS_WITH_GROUP = "user.id as id,name,password,flatNumber,profession,email,phone, user.photoset as photoset,
          attributeRow,similar,aboutMe,post, renter,sex,
          user_group.photoset as gphotoset, title, description, type";

	public static $SEARCH_BY_NAME = "select #selectField#, group_id from user
	        left join group_user on user.id = group_user.user_id left join
            user_group on group_user.group_id=user_group.id where user.name like ?
            and group_user.group_id in #groupId#  order by user.createAt desc ";

    public static $GET_LOGGEDIN_USER = "select #selectField#, group_id from user
	        left join group_user on user.id = group_user.user_id left join
            user_group on group_user.group_id=user_group.id inner join loggedUser
            on(user.id = loggedUser.userID) where
            group_user.group_id in #groupId# and userID != ? order by user.createAt desc ";


    // Example Select

	public static $SEARCH_BY_FLAT =  "select #selectField#,  group_id from user
	        left join group_user on user.id = group_user.user_id left join
            user_group on group_user.group_id=user_group.id where
            user.flatNumber = ? and group_user.group_id in #groupId#  order by user.createAt desc ";


    public static $SEARCH_BY_PROFESSION =  "select #selectField#,  group_id from user
	        left join group_user on user.id = group_user.user_id left join
            user_group on group_user.group_id=user_group.id where
            user.profession like ? and group_user.group_id in #groupId#  order by user.createAt desc ";


    public static $SEARCH_BY_GROUPID =  "select #selectField#, group_user.group_id from user
	        inner join (select user_id from group_user where group_user.group_id = ? ) as interested_ug
	        on user.id = interested_ug.user_id left join
	        group_user on user.id = group_user.user_id left join
            user_group  on group_user.group_id=user_group.id order by user.createAt desc ";


    /*
     *
     * select user.id, group_user.group_id from user inner join (select user_id from group_user where group_user.group_id = 2 ) as interested_ug on user.id = interested_ug.user_id left join
	        group_user on user.id = group_user.user_id left join
            user_group  on group_user.group_id=user_group.id order by user.createAt desc
     */


    public static $GROUP_MEMBER_COUNT =  "select count(*) as count from group_user where  group_user.group_id = ?";



    public static $SEARCH_BY_ALL =  "select #selectField#, group_id from user
	        left join group_user on user.id = group_user.user_id left join
            user_group on group_user.group_id=user_group.id where
             user.name like ?
	        and user.flatNumber like ? and user.profession like ? and user.post like ?
	        and group_user.group_id in #groupId#  order by user.createAt desc limit 100 ";


    public static $SEARCH_ALL_GROUP = "select * from user_group where parentGroup = ?";

    public static $GET_USER_GROUP = "select * from group_user left join user_group on group_user.group_id=user_group.id where group_user.user_id=?";

    public static $SEARCH_PROFESSION = "select * from profession where title like  ?";

    public static $GET_USER_GROUP_WITH_USER =
        "select user.id as id,name,password,flatNumber,profession,email,phone, user.photoset as photoset,
          attributeRow,similar,aboutMe,post, renter, sex, birthDay,
          user_group.photoset as gphotoset, title, description, type, group_id
            from user left join group_user on user.id = group_user.user_id  left join
            user_group on group_user.group_id=user_group.id where user.id=?";

    public static $INSERT_LOGGED_USER = 'insert into loggedUser(userID, chatID, lastSeen) values(? , ?, now())';

    public static $DELETE_LOGGED_USER = 'delete from loggedUser where userID = ?';


    public static $INSERT_INVITATION = 'insert into user(email, inviter, inviter_key) values(?,?,?)';


    public static $GET_USER_ON_INVITATION = 'select email from user where inviter=? and inviter_key = ?';


    public static $UPDATE_INVITED_USER = "update user set name = ? , password =? where email = ?";


    /**
	 * insert queries
	 */
	public static $INSERT_USER = "insert into user (name, email, password, createAt, updatedAt) values (?, ?, ?, now(), now())";

	public static $INSERT_GROUP_USER = "insert into group_user (group_id, user_id) values (?, ?)";

	/**
	 *
	 */
	public static $UPDATE_USER = "update user set flatNumber = ?, phone = ?, updatedAt = now() where id = ?";

	public static $UPDATE_USER_PROFILE = "update user set name = ?, aboutMe = ?, phone = ?, birthDay = ?, profession =? , post = ? , renter = ?, sex =?, updatedAt = now() where id = ?";

	public static $UPDATE_USER_IMAGE = "update user set photoset = ?, updatedAt = now() where id = ?";

	public static $UPDATE_USER_SECRET = "update user set secret = ?, updatedAt = now() where email = ?";

	public static $UPDATE_USER_PASSWORD = "update user set password = ?, updatedAt = now() where email = ?";

	public static $UPDATE_USER_PASSWORD_BY_ID = "update user set password = ?, updatedAt = now() where id = ?";


	/** REG PATTERN */

	public static $DUPLICATE_EMAIL_CHECKING = "/^Duplicate entry .*? for key 'email'$/";
	public static $DUPLICATE_PHONE_CHECKING = "/^Duplicate entry .*? for key 'phone'$/";



	/**
	 * @param $name
	 * @param $email
	 * @param $password
	 */
	public function saveUser($name, $email, $password)
	{
		try {
			$stmt = $this->adapter->createStatement(UserDao::$INSERT_USER, array($name, $email, $password));
			$stmt = $stmt->prepare();
			$stmt->execute();

			$stmt = null;
		} catch (\Exception $e){
			if(preg_match(UserDao::$DUPLICATE_EMAIL_CHECKING,  $e->getMessage())){
				return array('result' => 'failure', 'reason'=>'emailDup', 'email' => $email );
			}
		}
	}



    public function inviteUser($email, $inviter, $inviter_secret)
    {
        try {
            $stmt = $this->adapter->createStatement(UserDao::$INSERT_INVITATION, array($email, $inviter, $inviter_secret));
            $stmt = $stmt->prepare();
            $stmt->execute();

            $stmt = null;
            return null;
        } catch (\Exception $e){
            if(preg_match(UserDao::$DUPLICATE_EMAIL_CHECKING,  $e->getMessage())){
                return array('result' => 'failure', 'reason'=>'emailDup', 'email' => $email );
            }
        }
    }


    /**
     * @param $name
     * @param $email
     * @param $password
     */
    public function updateInvitedUser($name, $email, $password)
    {
        try {
            $stmt = $this->adapter->createStatement(UserDao::$UPDATE_INVITED_USER, array($name,$password, $email));
            $stmt = $stmt->prepare();
            $stmt->execute();

            $stmt = null;
        } catch (\Exception $e){
            if(preg_match(UserDao::$DUPLICATE_EMAIL_CHECKING,  $e->getMessage())){
                return array('result' => 'failure', 'reason'=>'emailDup', 'email' => $email );
            }
        }
    }

    public static $UPDATE_BLOCK_COUNT = 'update user set blocked_count = ? where id =?';

    public function updateBlockCount($id, $count){
        try {


            $stmt = $this->adapter->createStatement(UserDao::$UPDATE_BLOCK_COUNT, array($count, $id));
            $stmt = $stmt->prepare();
            $stmt->execute();
            $stmt = null;
        } catch (\Exception $e){

        }
    }

    public function alreadyBlocked($blocking_id, $blocked_id){

        $query = "select * from block_user where blocking_userid = ? and blocked_userid = ?";

        $stmt = $this->adapter->createStatement($query, array($blocking_id, $blocked_id));
        $stmt->prepare();
        $result = $stmt->execute();
        if ($result instanceof ResultInterface && $result->isQueryResult()) {
            $resultSet = new ResultSet();
            $resultSet->initialize($result);
            if($resultSet->count() > 0){
                return true;
            }
            return false;
        }
    }


    public function blockedAction($blocking_id, $blocked_id, $reason){
        echo $reason;
        $query = "insert into block_user(blocking_userid, blocked_userid, reason) values(?,?,?)";
        $stmt = $this->adapter->createStatement($query, array($blocking_id, $blocked_id, $reason));
        $stmt = $stmt->prepare();
        $stmt->execute();
        $stmt = null;
    }


    public function getBlockCount($blocked_id){
        $query = "select count(blocking_userid) as count from block_user where blocked_userid = ?";
        $stmt = $this->adapter->createStatement($query, array($blocked_id));
        $stmt->prepare();
        $result = $stmt->execute();
        if ($result instanceof ResultInterface && $result->isQueryResult()) {
            $resultSet = new ResultSet();
            $resultSet->initialize($result);
            if($resultSet->count() > 0){
                return $resultSet->current()->count;
            }
            return 0;
        }
    }


    public static $BLOCK_USER = 'update user set blocked = 1 where id =?';

    public function blockUser($id){
        try {
            $stmt = $this->adapter->createStatement(UserDao::$BLOCK_USER, array( $id));
            $stmt = $stmt->prepare();
            $stmt->execute();
            $stmt = null;
        } catch (\Exception $e){

        }
    }

	/**
	 * @param $name
	 * @param $aboutMe
	 * @param $phone
	 * @param $birthDay
	 * @param $profession
	 * @param $post
	 * @param $id
	 * @return array
	 */
	public function updateUser($name, $aboutMe, $phone, $birthDay, $profession, $post,$renter,$sex, $id)
	{
		try {

			$birthDay=date('Y-m-d', strtotime($birthDay));
			//$birthDay =  date_format($birthDay, 'Y-m-d');
			$stmt = $this->adapter->createStatement(UserDao::$UPDATE_USER_PROFILE, array($name, $aboutMe, $phone, $birthDay, $profession, $post,$renter,$sex, $id));
			$stmt = $stmt->prepare();
			$stmt->execute();
			$stmt = null;
            return null;
		} catch (\Exception $e){
			echo $e->getMessage();
			if(preg_match(UserDao::$DUPLICATE_PHONE_CHECKING,  $e->getMessage())){
				return array('result' => 'failure', 'reason'=>'phoneDup', 'phone' => $phone );
			}
		}
	}

	public function resetPassword( $email, $password)
	{
		try {
			$stmt = $this->adapter->createStatement(UserDao::$UPDATE_USER_PASSWORD, array($password, $email));
			$stmt = $stmt->prepare();
			$stmt->execute();
			$stmt = null;
		} catch (\Exception $e){
			throw $e;
		}
	}

	public function resetPasswordById( $id, $password)
	{
		try {
			$stmt = $this->adapter->createStatement(UserDao::$UPDATE_USER_PASSWORD_BY_ID, array($password, $id));
			$stmt = $stmt->prepare();
			$stmt->execute();
			$stmt = null;
		} catch (\Exception $e){
			throw $e;
		}
	}

	public function getUserByEmail($email){
		$stmt = $this->adapter->createStatement(UserDao::$SELECT_BY_EMAIL, array($email));
		$stmt->prepare();
		$result = $stmt->execute();
		if ($result instanceof ResultInterface && $result->isQueryResult()) {
			$resultSet = new ResultSet();
			$resultSet->initialize($result);
			if($resultSet->count() > 0){
				return $this->processUserObject($resultSet->current());
			}
			return null;
		}
	}

    public function getUserByEmailWithPassword($email){
        $stmt = $this->adapter->createStatement(UserDao::$SELECT_BY_EMAIL, array($email));
        $stmt->prepare();
        $result = $stmt->execute();
        if ($result instanceof ResultInterface && $result->isQueryResult()) {
            $resultSet = new ResultSet();
            $resultSet->initialize($result);
            if($resultSet->count() > 0){
                return $this->processUserObjectWithPassword($resultSet->current());
            }
            return null;
        }
    }


    public function recommendedUser($inviter, $inviter_secret){
        $stmt = $this->adapter->createStatement(UserDao::$GET_USER_ON_INVITATION, array($inviter, $inviter_secret));
        $stmt->prepare();
        $result = $stmt->execute();

        if ($result instanceof ResultInterface && $result->isQueryResult()) {
            $resultSet = new ResultSet();
            $resultSet->initialize($result);
            if($resultSet->count() > 0){
                return $resultSet->current()->email;
            }
            return null;
        }
    }

	public function getUserById($id){
		$stmt = $this->adapter->createStatement(UserDao::$SELECT_BY_ID, array($id));
		$stmt->prepare();
		$result = $stmt->execute();
		if ($result instanceof ResultInterface && $result->isQueryResult()) {
			$resultSet = new ResultSet();
			$resultSet->initialize($result);
			if($resultSet->count() > 0){
				return $this->processUserObject($resultSet->current());
			}
			return null;
		}
	}

    public function getUserByIdWithGroup($id){
        $stmt = $this->adapter->createStatement(UserDao::$GET_USER_GROUP_WITH_USER, array($id));
        $stmt->prepare();
        $result = $stmt->execute();
        if ($result instanceof ResultInterface && $result->isQueryResult()) {
            $resultSet = new ResultSet();
            $resultSet->initialize($result);

            if($resultSet->count() > 0){
                $users = $this->aggregateUserForGroups($resultSet);
                return $this->processUserObject($users[0]);
            }
            return null;
        }
    }

	public function getUserByUNP($email, $passwd){
		$stmt = $this->adapter->createStatement(UserDao::$SELECT_BY_EMAIL_PASSWORD, array($email, $passwd));
		$stmt->prepare();
		$result = $stmt->execute();
		if ($result instanceof ResultInterface && $result->isQueryResult()) {
			$resultSet = new ResultSet();
			$resultSet->initialize($result);
			if($resultSet->count() > 0){
				return $this->processUserObject($resultSet->current());
			}
			return null;
		}
	}

    private function getDefaultProfile(){
        return array(
            "tiny" => array("id" => 1, "type" => "tiny"),
            "feed" => array("id" => 2, "type" => "feed"),
            "profile" => array("id" => 3, "type" => "profile"),
        );
    }

    private function processUserObjectWithPassword($user){

        if( property_exists($user, 'photoset') && $user->photoset != null){
            $photoXml = $user->photoset;
            $reader = new Xml();
            $data  = $reader->fromString($photoXml);
            $user->photoarray = $data;
        } else {
            $user->photoarray = $this->getDefaultProfile();
        }

        if( property_exists($user, 'birthDay') && $user->birthDay != null){
            $user->birthDay = date('F d, Y',strtotime($user->birthDay));
        }
        return $user;
    }

	private function processUserObject($user){
        if( property_exists($user, 'password')){
            unset ($user->password);
        }

        if( property_exists($user, 'photoset') && $user->photoset != null){
            $photoXml = $user->photoset;
            $user->photoset = null;
            $reader = new Xml();
            $data  = $reader->fromString($photoXml);
            $user->photoarray = $data;
        } else {
            $user->photoarray = $this->getDefaultProfile();
        }

		if( property_exists($user, 'birthDay') && $user->birthDay != null){
			$user->birthDay = date('F d, Y',strtotime($user->birthDay));
		}
		return $user;
	}


	public function getUserByUNS($email, $secret){
		$stmt = $this->adapter->createStatement(UserDao::$SELECT_BY_EMAIL_SECRET, array($email, $secret));
		$stmt->prepare();
		$result = $stmt->execute();
		if ($result instanceof ResultInterface && $result->isQueryResult()) {
			$resultSet = new ResultSet();
			$resultSet->initialize($result);
			if($resultSet->count() > 0){
				return $this->processUserObject($resultSet->current());
			}
			return null;
		}
	}


	public function saveAdditionalUser($user, $apartment, $block, $flatNo, $phoneNo){
		$connection = $this->adapter->driver->getConnection();
		try {
			$connection->beginTransaction();
			$stmt = $this->adapter->createStatement(UserDao::$INSERT_GROUP_USER, array(  $apartment ,   $user));
			$stmt = $stmt->prepare();
			$stmt->execute();

			$stmt = $this->adapter->createStatement(UserDao::$INSERT_GROUP_USER, array( $block ,   $user));
			$stmt = $stmt->prepare();
			$stmt->execute();

			$stmt = $this->adapter->createStatement(UserDao::$UPDATE_USER, array($flatNo ,  $phoneNo, $user));
			$stmt = $stmt->prepare();
			$stmt->execute();
			$stmt = null;
			$connection->commit();
		} catch(\Exception $e){
			$connection->rollback();
			if(preg_match(UserDao::$DUPLICATE_PHONE_CHECKING,  $e->getMessage())){
				return array('result' => 'fail', 'reason'=>'phoneDup');
			}
			throw $e;
		}

	}

	public function getProfileImage($id, $type){
		$xmlArray = $this->getProfileImageXml($id);
		return $xmlArray[$type];
	}

	public function getProfileImageXml($id){
		$stmt = $this->adapter->createStatement(UserDao::$SELECT_BY_ID, array($id));
		$stmt->prepare();
		$result = $stmt->execute();
		if ($result instanceof ResultInterface && $result->isQueryResult()) {
			$resultSet = new ResultSet();
			$resultSet->initialize($result);
			if($resultSet->count() > 0){
				$result =  $resultSet->current();
				$image =  $result->$photoset;
				if($image != null){
					$reader = new Xml();
					$data   = $reader->fromString($image);
					return $data;
				}
			}
			return null;
		}
	}

	public function saveProfileImage($userId, $photoXml){
		$stmt = $this->adapter->createStatement(UserDao::$UPDATE_USER_IMAGE, array($photoXml, $userId));
		$stmt->prepare();
		$result = $stmt->execute();
		$stmt = null;
	}

	public function saveUserSecret($email, $secret){
		$stmt = $this->adapter->createStatement(UserDao::$UPDATE_USER_SECRET, array($secret ,  $email));
		$stmt = $stmt->prepare();
		$stmt->execute();
		$stmt = null;
	}

	public function getRecentlyAddedUser(){
		$stmt = $this->adapter->createStatement(UserDao::$RECENT_USERS);
		$stmt->prepare();
		$result = $stmt->execute();
		if ($result instanceof ResultInterface && $result->isQueryResult()) {
            $resultSet = new ResultSet();
            $resultSet->initialize($result);
            if($resultSet->count() > 0){
                $users = $this->aggregateUserForGroups($resultSet);
                return $this->processesUserArray($users);
            }
            return null;
		}
	}

	public function searchUserByName($name, $groupIds){


        $query = str_replace('#groupId#', '('.implode(',', array_values($groupIds)).')', UserDao::$SEARCH_BY_NAME);

        $query = str_replace('#selectField#',UserDao::$SELECT_USER_FIELDS_WITH_GROUP, $query);


		$stmt = $this->adapter->createStatement( $query, array("%".$name."%"));
		$stmt->prepare();
		$result = $stmt->execute();
        return $this->processUsersList($result);

	}


    private function processUsersList($result){
        if ($result instanceof ResultInterface && $result->isQueryResult()) {
            $resultSet = new ResultSet();
            $resultSet->initialize($result);

            if($resultSet->count() > 0){
                $users = $this->aggregateUserForGroups($resultSet);
                foreach($users as $user){
                    $this->processUserObject($user);
                }
                return $users;
            }
            return null;
        }
    }


    private function aggregateUserForGroups($result){
        $resultSet = new ResultSet();
        $resultSet->initialize($result);

        $groups = null;
        $curUser = null ;
        if($resultSet->count() > 0){
            $resultArray = array();
            foreach($resultSet as $user){


                if($curUser == null || $curUser->id  != $user->id){
                    $groups = array();
                    $curUser = $user;
                    array_push($resultArray, $curUser) ;
                    $curUser->groups = array();
                }

                array_push($curUser->groups , array(
                    'id' => $user->group_id,
                    'name' => $user->title,
                    'desc' => $user->description,
                    'type' => $user->type,
                ));

            }
            return $resultArray;
        }
        return null;
    }

    private function processesUserArray($result){
        $resultSet = new ResultSet();
        $resultSet->initialize($result);

        if($resultSet->count() > 0){
            $resultArray = array();
            foreach($resultSet as $user){
                array_push($resultArray, $this->processUserObject($user));
            }
            return $resultArray;
        }
        return null;
    }

	public function searchUserByFlatNo($flatNo, $groupIds){


        $query = str_replace('#groupId#', '('.implode(',', array_values($groupIds)).')', UserDao::$SEARCH_BY_FLAT);

        $query = str_replace('#selectField#',UserDao::$SELECT_USER_FIELDS_WITH_GROUP, $query);

        $stmt = $this->adapter->createStatement( $query, array($flatNo));
        $stmt->prepare();
        $result = $stmt->execute();
        return $this->processUsersList($result);
	}

	public function searchUserByProfession( $profession, $groupIds){

        $query = str_replace('#groupId#', '('.implode(',', array_values($groupIds)).')', UserDao::$SEARCH_BY_PROFESSION);

        $query = str_replace('#selectField#',UserDao::$SELECT_USER_FIELDS_WITH_GROUP, $query);

        $stmt = $this->adapter->createStatement( $query, array($profession));
        $stmt->prepare();
        $result = $stmt->execute();
        return $this->processUsersList($result);

	}


    public function searchUserByAll($name, $flatNo, $profession, $post, $groupId){

        $name = $name? '%'. $name . '%' : '%%';
        $flatNo = $flatNo ? '%'.$flatNo. '%' : '%%';
        $profession = $profession ? '%'.$profession. '%' : '%%';
        $post = $post ?'%'. $post. '%' : '%%';
        $query = str_replace('#groupId#', '('.implode(',', array_values($groupId)).')', UserDao::$SEARCH_BY_ALL);

        $query = str_replace('#selectField#',UserDao::$SELECT_USER_FIELDS_WITH_GROUP, $query);


        $stmt = $this->adapter->createStatement( $query, array($name, $flatNo, $profession, $post));
        $stmt->prepare();
        $result = $stmt->execute();
        return $this->processUsersList($result);
    }


	public function getAllBlock($apartmentID){

		$stmt = $this->adapter->createStatement(UserDao::$SEARCH_ALL_GROUP, array($apartmentID));
		$stmt->prepare();
		$result = $stmt->execute();
		if ($result instanceof ResultInterface && $result->isQueryResult()) {
			$resultSet = new ResultSet();
			$resultSet->initialize($result);
			if($resultSet->count() > 0){
				return $resultSet;
			}
			return null;
		}
	}



    public function getAllGroupMates($groupId){
        $query = str_replace('#selectField#',UserDao::$SELECT_USER_FIELDS_WITH_GROUP, UserDao::$SEARCH_BY_GROUPID);

        $stmt = $this->adapter->createStatement($query, array($groupId));
        $stmt->prepare();
        $result = $stmt->execute();
        return $this->processUsersList($result);
    }


    public function getGroupMatesCount($groupId){

        $stmt = $this->adapter->createStatement(UserDao::$GROUP_MEMBER_COUNT, array($groupId));
        $stmt->prepare();
        $result = $stmt->execute();
        if ($result instanceof ResultInterface && $result->isQueryResult()) {
            $resultSet = new ResultSet();
            $resultSet->initialize($result);
            if($resultSet->count() > 0){
                return $resultSet->current()->count;
            }
            return null;
        }
    }



	public function getAllFlat($block){

		$stmt = $this->adapter->createStatement(UserDao::$SEARCH_ALL_GROUP, array($block));
		$stmt->prepare();
		$result = $stmt->execute();
		if ($result instanceof ResultInterface && $result->isQueryResult()) {
			$resultSet = new ResultSet();
			$resultSet->initialize($result);
			if($resultSet->count() > 0){
				return $resultSet;
			}
			return null;
		}
	}

	public function getAllProfession($title){

		$stmt = $this->adapter->createStatement(UserDao::$SEARCH_PROFESSION, array($title));
		$stmt->prepare();
		$result = $stmt->execute();
		if ($result instanceof ResultInterface && $result->isQueryResult()) {
			$resultSet = new ResultSet();
			$resultSet->initialize($result);
			if($resultSet->count() > 0){
				return $resultSet;
			}
			return null;
		}
	}




    public function getAllGroup($userId){

        $stmt = $this->adapter->createStatement(UserDao::$GET_USER_GROUP, array($userId));
        $stmt->prepare();
        $result = $stmt->execute();
        if ($result instanceof ResultInterface && $result->isQueryResult()) {
            $resultSet = new ResultSet();
            $resultSet->initialize($result);
            if($resultSet->count() > 0){
                return $resultSet;
            }
            return null;
        }
    }


    public function getAllLoggedinUser($groupId, $userID){

        $query = str_replace('#groupId#', '('.implode(',', array_values($groupId)).')', UserDao::$GET_LOGGEDIN_USER);

        $query = str_replace('#selectField#',UserDao::$SELECT_USER_FIELDS_WITH_GROUP .", chatID ", $query);


        $stmt = $this->adapter->createStatement( $query, array($userID));
        $stmt->prepare();
        $result = $stmt->execute();
        return $this->processUsersList($result);
    }

    public function saveLoggedinUser($userID, $chatId){
        $this->removeLoggedinUser($userID);
        $stmt = $this->adapter->createStatement(UserDao::$INSERT_LOGGED_USER, array($userID ,  $chatId));
        $stmt = $stmt->prepare();
        $stmt->execute();
        $stmt = null;
    }


    public function updateTime($userID, $chatId){
        $this->removeLoggedinUser($userID);
        $stmt = $this->adapter->createStatement(UserDao::$INSERT_LOGGED_USER, array($userID ,  $chatId));
        $stmt = $stmt->prepare();
        $stmt->execute();
        $stmt = null;
    }

    public function removeLoggedinUser($userID){
        $stmt = $this->adapter->createStatement(UserDao::$DELETE_LOGGED_USER, array($userID ));
        $stmt = $stmt->prepare();
        $stmt->execute();
        $stmt = null;
    }

    public function saveChat($fromUserId, $toUserId, $message){

        $query = "insert into chat(from_userid, to_userid, chat, insert_time) values(?,?,?,now())";
        $stmt = $this->adapter->createStatement($query, array($fromUserId, $toUserId,$message ));
        $stmt = $stmt->prepare();
        $stmt->execute();
        $stmt = null;
    }

    public function getChat($oneUser, $secondUser){

        $query = "select user.id as id,name, user.photoset as photoset, chat.chat, chat.insert_time
                  as insert_time
                  from chat  inner join (select * from user where id = ? or id = ? ) as user
                     on(user.id = chat.from_userid) where (from_userid = ? and
                     to_userid = ?) or (to_userid = ? and
                     from_userid = ?) order by chat.insert_time asc";
        $stmt = $this->adapter->createStatement($query, array($oneUser, $secondUser,
            $oneUser, $secondUser, $oneUser, $secondUser));
        $stmt->prepare();
        $result = $stmt->execute();
        if ($result instanceof ResultInterface && $result->isQueryResult()) {
            $resultSet = new ResultSet();
            $resultSet->initialize($result);
            if($resultSet->count() > 0){
                $users = ($resultSet);
                $result = array();
                foreach($users as $user){

                    if( property_exists($user, 'insert_time') && $user->insert_time != null){
                        $user->insert_time = date('M d, g:i a',strtotime($user->insert_time));
                    }
                    array_push($result, $this->processUserObject($user)) ;
                }
                return $result;
            }
            return null;
        }
    }



}

?>
